package com.zdb.n1.repository;

import com.zdb.n1.entity.ExerciseRecord;
import com.zdb.n1.entity.ExerciseType;
import com.zdb.n1.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Repository
public interface ExerciseRecordRepository extends JpaRepository<ExerciseRecord, Long> {

    List<ExerciseRecord> findByUserOrderByStartTimeDesc(User user);

    Page<ExerciseRecord> findByUserOrderByStartTimeDesc(User user, Pageable pageable);

    List<ExerciseRecord> findByUserAndStartTimeBetweenOrderByStartTimeDesc(
            User user, Date startDate, Date endDate);

    List<ExerciseRecord> findByUserAndExerciseTypeOrderByStartTimeDesc(User user, ExerciseType exerciseType);

    @Query("SELECT SUM(e.durationMinutes) FROM ExerciseRecord e WHERE e.user = ?1")
    Integer getTotalDurationByUser(User user);

    @Query("SELECT SUM(e.durationMinutes) FROM ExerciseRecord e WHERE e.user = ?1 AND e.startTime BETWEEN ?2 AND ?3")
    Integer getTotalDurationByUserAndDateRange(User user, Date startDate, Date endDate);

    @Query("SELECT SUM(e.caloriesBurned) FROM ExerciseRecord e WHERE e.user = ?1")
    Double getTotalCaloriesByUser(User user);

    @Query("SELECT SUM(e.caloriesBurned) FROM ExerciseRecord e WHERE e.user = ?1 AND e.startTime BETWEEN ?2 AND ?3")
    Double getTotalCaloriesByUserAndDateRange(User user, Date startDate, Date endDate);

    @Query("SELECT e.exerciseType, COUNT(e) FROM ExerciseRecord e WHERE e.user = ?1 GROUP BY e.exerciseType")
    List<Object[]> getExerciseTypeDistribution(User user);

    Page<ExerciseRecord> findByUser(User user, Pageable pageable);

    List<ExerciseRecord> findByUser(User user);

    List<ExerciseRecord> findByStartTimeAfter(Date date);

    /**
     * 统计与指定运动类型关联的运动记录数量
     * @param exerciseType 运动类型
     * @return 关联记录数
     */
    long countByExerciseType(ExerciseType exerciseType);
    
    /**
     * 删除与指定运动类型关联的所有运动记录
     * @param exerciseType 运动类型
     */
    void deleteByExerciseType(ExerciseType exerciseType);
} 